package com.hongshan.wallet.base

import android.databinding.DataBindingUtil
import android.databinding.ViewDataBinding
import android.support.v4.view.PagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import me.goldze.mvvmhabit.base.BaseViewModel

/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.base
 * @author   : zhangxx
 * @data     : 2019/3/21
 * @email    : qq957413212@hotmail.com
 */
abstract class BasePagerAdapter<T : BaseViewModel> : PagerAdapter() {

    override fun isViewFromObject(p0: View, p1: Any) = p0 == p1

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val binding = DataBindingUtil.inflate<ViewDataBinding>(
            LayoutInflater.from(container.context),
            getLayoutId(position),
            null,
            false
        )
        val vm = getViewModel(position)
        binding.setVariable(getBrId(position), vm)
        binding.executePendingBindings()
        container.addView(binding.root)
        dispose(binding.root, vm)
        return binding.root
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        container.removeView(`object` as View)
    }

    open fun dispose(view: View, vm: T) {}

    abstract fun getLayoutId(position: Int):Int

    abstract fun getBrId(position: Int):Int

    abstract fun getViewModel(position: Int):T
}